package com.seeyon.apps.kkSample.manager.impl;

import com.seeyon.apps.kkSample.config.KKESignConfig;
import com.seeyon.apps.kkSample.manager.KKEsignContractFileSignManager;
import com.seeyon.apps.kkSample.po.SHKKResult;
import com.seeyon.apps.kkSample.utils.cap4.Cap4FormUtil;
import com.seeyon.apps.kkSample.utils.http.HttpUtil;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.util.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;

import java.util.*;

/**
 * 合同文件签署服务API - V3
 */
public class KKEsignContractFileSignManagerImpl implements KKEsignContractFileSignManager {
    private static final Log LOG = CtpLogFactory.getLog(KKEsignContractFileSignManagerImpl.class);
    private final EnumManager enumManager = (EnumManager) AppContext.getBean("enumManagerNew");

    /**
     * 签署流程 - 发起类 - 基于文件发起签署
     *
     * @param fileIdList
     * @param formBean
     * @param formDataMasterBean
     * @param appUrl
     * @param OAurl
     * @param headerParams
     * @return
     */
    @Override
    public SHKKResult createByFile(List<String> fileIdList, FormBean formBean, FormDataMasterBean formDataMasterBean, String appUrl, String OAurl, Map<String, Object> headerParams) {
        LOG.info("====================[签署流程] createByFile satrt");
        //1、请求体参数
        Map<String, Object> params = new HashMap<>();
        /**
         *  待签署文件信息 + 签署区信息
         */
        List<Map<String, Object>> docs = new ArrayList<>();
        List<Map<String, Object>> signFields = new ArrayList<>();
        //印章类型
        String sealTypeECode = getEnumCode(String.valueOf(Cap4FormUtil.getFieldValue("印章类型", formDataMasterBean)));
        String sealType = dyConvertForSealType(sealTypeECode);
        for (int i = 0; i < fileIdList.size(); ++i) {
            //待签署文件信息
            Map<String, Object> doc = new HashMap<>();
            //签署区信息
            Map<String, Object> signField = new HashMap<>();
            //待签署文件ID
            doc.put("fileId", fileIdList.get(i));
            docs.add(doc);
            //签署区所在待签署文件ID
            signField.put("fileId", fileIdList.get(i));
            //签署区类型
            signField.put("signFieldType", 0);
            //签章区配置项
            Map<String, Object> normalSignFieldConfig = new HashMap<>();
            //是否自由签章
            /**
             * 是否自由签章，默认值 false
             * true - 是，false - 否
             * 补充说明：
             * 自由签章 指不限制印章、签署位置、签章样式（单页、骑缝）、和签章个数。
             * 自由签章模式下，无需传normalSignFieldConfig对象下的其他参数。
             */
            normalSignFieldConfig.put("freeMode", true);
            normalSignFieldConfig.put("orgSealBizTypes", sealType);
            signField.put("normalSignFieldConfig", normalSignFieldConfig);
            signFields.add(signField);
        }
        /**
         * 签署流程配置项
         */
        Map<String, Object> signFlowConfig = new HashMap<>();
        //合同名称
        String signFlowTitle = Cap4FormUtil.getFieldValue("合同名称", formDataMasterBean).toString();
        //签署流程主题
        signFlowConfig.put("signFlowTitle", signFlowTitle);
        //自动开启签署流程
        signFlowConfig.put("autoStart", true);
        //签署方签署完成后流程自动完结
        signFlowConfig.put("autoFinish", true);
        Map<String, Object> signConfig = new HashMap<>();
        //签署终端类型:网页 签署终端类型，默认值1和2（英文逗号分隔）1 - 网页（自适配H5/PC样式），2 - 支付宝
        signConfig.put("availableSignClientTypes", "1");

        signFlowConfig.put("signConfig", signConfig);
        signFlowConfig.put("notifyUrl", OAurl + KKESignConfig.CALL_BACK_ADDRESS);

        /**
         * 签署方信息
         */
        List<Map> signers = new ArrayList<>();
        //新签署方信息
        //合同名称
        String signerTypeV = getEnumValue(Long.valueOf(String.valueOf(Cap4FormUtil.getFieldValue("用户类型", formDataMasterBean))));
        LOG.info("=======================[signerTypeV]" + signerTypeV);
        //合同名称    我方先签署 =1 对方先签署=0
        String signOrderV = "1";
        LOG.info("=======================[signOrderV]" + Cap4FormUtil.getFieldValue("盖章顺序", formDataMasterBean));
        if (Objects.nonNull(Cap4FormUtil.getFieldValue("盖章顺序", formDataMasterBean))) {
            signOrderV = getEnumKey(Long.valueOf(String.valueOf(Cap4FormUtil.getFieldValue("盖章顺序", formDataMasterBean))));
        }
        LOG.info("=======================[signOrderV] " + signOrderV);
        //添加签署方信息
        if (StringUtils.isNotBlank(signerTypeV)) {
            LOG.info("=======================[signOrderV] 单方");
            Map<String, Object> signer = new HashMap<>();
            String tzfs = "";
            if (Objects.nonNull(Cap4FormUtil.getFieldValue("通知方式", formDataMasterBean))) {
                tzfs = getEnumValue(Long.valueOf(String.valueOf(Cap4FormUtil.getFieldValue("通知方式", formDataMasterBean))));
            }
            String qsfxm = String.valueOf(Cap4FormUtil.getFieldValue("个人名称", formDataMasterBean));
            String qsfzjh = String.valueOf(Cap4FormUtil.getFieldValue("证件号码", formDataMasterBean));
            String qsfsjh = String.valueOf(Cap4FormUtil.getFieldValue("手机号码", formDataMasterBean));
            String qsfyx = String.valueOf(Cap4FormUtil.getFieldValue("邮箱地址", formDataMasterBean));
            String qsfqsgs = String.valueOf(Cap4FormUtil.getFieldValue("单位名称", formDataMasterBean));
            //签署方的通知方式
            Map<String, Object> noticeConfig = new HashMap<>();
            //签署方的通知方式
            String noticeTypes = "";
            //经办人账号标识，手机号或邮箱
            String psnAccount = "";
            if (tzfs.equals("短信")) {
                noticeTypes = "1";
                psnAccount = psnAccount + qsfsjh;
            } else if (tzfs.equals("邮箱")) {
                noticeTypes = "2";
                psnAccount = psnAccount + qsfyx;
            }
            noticeConfig.put("noticeTypes", noticeTypes);

            //签署人信息
            Map<String, Object> psnInfo = new HashMap<>();
            //签署人姓名
            psnInfo.put("psnName", qsfxm);
            //签署人证件号
            psnInfo.put("psnIDCardNum", qsfzjh);

            int signerType = 0;
            //机构签署
            if (signerTypeV.equals("机构")) {
                signerType = 1;
                Map<String, Object> orgSignerInfo = new HashMap<>();
                Map<String, Object> transactorInfo = new HashMap<>();
                transactorInfo.put("psnAccount", psnAccount);
//                transactorInfo.put("psnInfo", psnInfo);
                //机构名称
                orgSignerInfo.put("orgName", qsfqsgs);
                //机构经办人信息
                orgSignerInfo.put("transactorInfo", transactorInfo);
                signer.put("orgSignerInfo", orgSignerInfo);
            } else if (signerTypeV.equals("个人")) {
                signerType = 0;
                //个人签署方信息
                Map<String, Object> psnSignerInfo = new HashMap<>();
                psnInfo.put("psnMobile", qsfsjh);
//                psnSignerInfo.put("psnInfo", psnInfo);
                psnSignerInfo.put("psnAccount", psnAccount);
                signer.put("psnSignerInfo", psnSignerInfo);
            }
            signer.put("noticeConfig", noticeConfig);
            signer.put("signerType", signerType);
            signer.put("signFields", signFields);
            Map signers_signConfig = new HashMap();
            // 签署顺序
            if (signOrderV.equals("1")) {
                signers_signConfig.put("signOrder", "1");
            } else {
                signers_signConfig.put("signOrder", 2);
            }

            signer.put("signConfig", signers_signConfig);
            signers.add(signer);
        }
        //新签署方信息
        //合作方用户类型
        String partner_signerType = "";
        if (Objects.nonNull(Cap4FormUtil.getFieldValue("合作方用户类型", formDataMasterBean))) {
            partner_signerType = getEnumValue(Long.valueOf(String.valueOf(Cap4FormUtil.getFieldValue("合作方用户类型", formDataMasterBean))));
        }
        //添加签署方信息
        if (StringUtils.isNotBlank(partner_signerType)) {
            LOG.info("=======================[signOrderV] 多方");
            Map<String, Object> signer = new HashMap<>();
            String tzfs = "";
            if (Objects.nonNull(Cap4FormUtil.getFieldValue("通知方式", formDataMasterBean))) {
                tzfs = getEnumValue(Long.valueOf(String.valueOf(Cap4FormUtil.getFieldValue("合作方通知方式", formDataMasterBean))));
            }
            String qsfxm = String.valueOf(Cap4FormUtil.getFieldValue("合作方个人名称", formDataMasterBean));
            String qsfzjh = String.valueOf(Cap4FormUtil.getFieldValue("合作方证件号码", formDataMasterBean));
            String qsfsjh = String.valueOf(Cap4FormUtil.getFieldValue("合作方手机号码", formDataMasterBean));
            String qsfyx = String.valueOf(Cap4FormUtil.getFieldValue("合作方邮箱地址", formDataMasterBean));
            String qsfqsgs = String.valueOf(Cap4FormUtil.getFieldValue("合作方单位名称", formDataMasterBean));
            //签署方的通知方式
            Map<String, Object> noticeConfig = new HashMap<>();
            //签署方的通知方式
            String noticeTypes = "";
            //经办人账号标识，手机号或邮箱
            String psnAccount = "";
            if (tzfs.equals("短信")) {
                noticeTypes = "1";
                psnAccount = psnAccount + qsfsjh;
            } else if (tzfs.equals("邮箱")) {
                noticeTypes = "2";
                psnAccount = psnAccount + qsfyx;
            }
            noticeConfig.put("noticeTypes", noticeTypes);

            //签署人信息
            Map<String, Object> psnInfo = new HashMap<>();
            //签署人姓名
            psnInfo.put("psnName", qsfxm);
            //签署人证件号
            psnInfo.put("psnIDCardNum", qsfzjh);

            int signerType = 0;
            //机构签署
            if (partner_signerType.equals("机构")) {
                signerType = 1;
                Map<String, Object> orgSignerInfo = new HashMap<>();
                Map<String, Object> transactorInfo = new HashMap<>();
                transactorInfo.put("psnAccount", psnAccount);
//                transactorInfo.put("psnInfo", psnInfo);
                //机构名称
                orgSignerInfo.put("orgName", qsfqsgs);
                //机构经办人信息
                orgSignerInfo.put("transactorInfo", transactorInfo);
                signer.put("orgSignerInfo", orgSignerInfo);
            } else if (partner_signerType.equals("个人")) {
                signerType = 0;
                //个人签署方信息
                Map<String, Object> psnSignerInfo = new HashMap<>();
                psnInfo.put("psnMobile", qsfsjh);
//                psnSignerInfo.put("psnInfo", psnInfo);
                psnSignerInfo.put("psnAccount", psnAccount);
                signer.put("psnSignerInfo", psnSignerInfo);
            }
            signer.put("noticeConfig", noticeConfig);
            signer.put("signerType", signerType);
            signer.put("signFields", signFields);
            Map signers_signConfig = new HashMap();
            // 签署顺序
            if (signOrderV.equals("0")) {
                signers_signConfig.put("signOrder", 1);
            } else {
                signers_signConfig.put("signOrder", 2);
            }
            signer.put("signConfig", signers_signConfig);
            signers.add(signer);
        }
//        LOG.info("============电子签个人名称"+formBean.getFieldBeanByDisplay("电子签个人名称"));
//        if (Objects.nonNull(formBean.getFieldBeanByDisplay("电子签个人名称"))) {
//            FormTableBean formSonTableBean = formBean.getFormTableBeanByFieldName(formBean.getFieldBeanByDisplay("电子签个人名称").getName());
//            List<FormDataSubBean> formDataSubBeans = formDataMasterBean.getSubData(formSonTableBean.getTableName());
//            for (FormDataSubBean formDataSubBean : formDataSubBeans) {
//                Map<String, Object> signer = new HashMap<>();
//                String qslx = getEnumValue(Long.valueOf(String.valueOf(formDataSubBean.getFieldValue(formBean.getFieldBeanByDisplay("电子签用户类型").getName()))));
//                String tzfs = getEnumValue(Long.valueOf(String.valueOf(formDataSubBean.getFieldValue(formBean.getFieldBeanByDisplay("电子签通知方式").getName()))));
//                String qsfxm = (String) formDataSubBean.getFieldValue(formBean.getFieldBeanByDisplay("电子签个人名称").getName());
//                String qsfzjh = (String) formDataSubBean.getFieldValue(formBean.getFieldBeanByDisplay("电子签证件号码").getName());
//                String qsfsjh = (String) formDataSubBean.getFieldValue(formBean.getFieldBeanByDisplay("电子签手机号码").getName());
//                String qsfyx = (String) formDataSubBean.getFieldValue(formBean.getFieldBeanByDisplay("电子签邮箱地址").getName());
//                String qsfqsgs = (String) formDataSubBean.getFieldValue(formBean.getFieldBeanByDisplay("电子签单位名称").getName());
//                // 签署顺序
//                String signOrder = String.valueOf(formDataSubBean.getFieldValue(formBean.getFieldBeanByDisplay("电子签顺序").getName()));
//                //签署方的通知方式
//                Map<String, Object> noticeConfig = new HashMap<>();
//                //签署方的通知方式
//                String noticeTypes = "";
//                //经办人账号标识，手机号或邮箱
//                String psnAccount = "";
//                if (tzfs.equals("短信")) {
//                    noticeTypes = "1";
//                    psnAccount = psnAccount + qsfsjh;
//                } else if (tzfs.equals("邮箱")) {
//                    noticeTypes = "2";
//                    psnAccount = psnAccount + qsfyx;
//                }
//                noticeConfig.put("noticeTypes", noticeTypes);
//
//                //签署人信息
//                Map<String, Object> psnInfo = new HashMap<>();
//                //签署人姓名
//                psnInfo.put("psnName", qsfxm);
//                //签署人证件号
//                psnInfo.put("psnIDCardNum", qsfzjh);
//
//                int signerType = 0;
//                //机构签署
//                if (qslx.equals("机构")) {
//                    signerType = 1;
//                    Map<String, Object> orgSignerInfo = new HashMap<>();
//                    Map<String, Object> transactorInfo = new HashMap<>();
//                    transactorInfo.put("psnAccount", psnAccount);
////                transactorInfo.put("psnInfo", psnInfo);
//                    //机构名称
//                    orgSignerInfo.put("orgName", qsfqsgs);
//                    //机构经办人信息
//                    orgSignerInfo.put("transactorInfo", transactorInfo);
//                    signer.put("orgSignerInfo", orgSignerInfo);
//                } else if (qslx.equals("个人")) {
//                    signerType = 0;
//                    //个人签署方信息
//                    Map<String, Object> psnSignerInfo = new HashMap<>();
//                    psnInfo.put("psnMobile", qsfsjh);
////                psnSignerInfo.put("psnInfo", psnInfo);
//                    psnSignerInfo.put("psnAccount", psnAccount);
//                    signer.put("psnSignerInfo", psnSignerInfo);
//                }
//                signer.put("noticeConfig", noticeConfig);
//                signer.put("signerType", signerType);
//                signer.put("signFields", signFields);
//                Map signers_signConfig = new HashMap();
//                signers_signConfig.put("signOrder", signOrder);
//                signer.put("signConfig", signers_signConfig);
//                signers.add(signer);
//            }
//        }

        params.put("docs", docs);
        params.put("signFlowConfig", signFlowConfig);
        params.put("signers", signers);

        //2、请求地址
        String url = appUrl + KKESignConfig.CREATE_BY_FILE;
        LOG.info("================url=" + url);
        LOG.info("================headerParams=" + headerParams);
        LOG.info("================params=" + params);
        return JSONUtil.parseJSONString(HttpUtil.doPost(url, headerParams, JSONUtil.toJSONString(params)), SHKKResult.class);
    }

    /**
     * 获得下拉选项对应的值
     *
     * @param enumId
     * @return
     */
    public String getEnumValue(Long enumId) {
        EnumManager enumManager = (EnumManager) AppContext.getBean("enumManagerNew");
        CtpEnumItem ctpEnumItem = enumManager.getEnumItem(enumId);
        return ctpEnumItem.getShowvalue();
    }

    /**
     * 获得下拉选项对应的值
     *
     * @param enumId
     * @return
     */
    public String getEnumKey(Long enumId) {
        EnumManager enumManager = (EnumManager) AppContext.getBean("enumManagerNew");
        CtpEnumItem ctpEnumItem = enumManager.getEnumItem(enumId);
        LOG.info("=======================[ctpEnumItem]" + ctpEnumItem);
        return ctpEnumItem.getEnumvalue();
    }

    /**
     * 签署流程 - 发起类 - 获取签署页面链接
     *
     * @param appUrl
     * @param headerParams
     * @param signFlowId
     * @param psnAccount
     * @return
     */
    @Override
    public SHKKResult signUrl(String appUrl, Map<String, Object> headerParams, String signFlowId, String psnAccount) {
        //1、请求体参数
        Map<String, Object> params = new HashMap<String, Object>();
        //签署流程ID
        params.put("signFlowId", signFlowId);
        //链接类型 1 - 预览链接（仅限查看，不能签署）， 2 - 签署链接
        params.put("urlType", 2);// 签署链接
        //签署操作人
        Map<String, Object> operator = new HashMap<String, Object>();
        operator.put("psnAccount", psnAccount);
        params.put("operator", operator);
        //2、请求地址
        String url = appUrl + "/v3/sign-flow/" + signFlowId + "/sign-url";
        //3、发送请求
        return JSONUtil.parseJSONString(HttpUtil.doPost(url, headerParams, params), SHKKResult.class);
    }

    /**
     * 签署流程 - 下载类 - 下载已签署文件及附属材料
     *
     * @param appUrl
     * @param headerParams
     * @param signFlowId
     * @return
     */
    @Override
    public SHKKResult fileDownLoadUrl(String appUrl, Map<String, Object> headerParams, String signFlowId) {
        Map<String, Object> params = new HashMap<String, Object>();
        String url = appUrl + "/v3/sign-flow/" + signFlowId + "/file-download-url";
        return JSONUtil.parseJSONString(HttpUtil.doGet(url, headerParams, params), SHKKResult.class);
    }

    /**
     * 签署流程 - 查询类 - 查询签署流程详情
     *
     * @param appUrl
     * @param headerParams
     * @param signFlowId
     * @return
     */
    @Override
    public SHKKResult detail(String appUrl, Map<String, Object> headerParams, String signFlowId) {
        Map<String, Object> params = new HashMap<String, Object>();
        String url = appUrl + "/v3/sign-flow/" + signFlowId + "/detail";
        return JSONUtil.parseJSONString(HttpUtil.doGet(url, headerParams, params), SHKKResult.class);
    }

    /**
     * @param enumItemId 枚举id
     * @return 枚举编码
     */
    public String getEnumCode(String enumItemId) {
        CtpEnumItem item = enumManager.getEnumItem(Long.valueOf(enumItemId));
        if (null != item) {
            return item.getEnumItemCode();
        }

        return null;
    }

    /**
     * 印章类型转换
     *
     * @param sealType 印章类型
     *                 CONTRACT -合同专用章，
     *                 FINANCE -财务章，
     *                 PERSONNEL -人事专用章，
     *                 PUBLIC -公章
     * @return
     */
    public String dyConvertForSealType(String sealType) {
        if (StringUtils.isNotBlank(sealType)) {
            switch (sealType) {
                case "commonSeal":
                    sealType = "PUBLIC";
                    break;
                case "personnel":
                    sealType = "PERSONNEL";
                    break;
                case "contractSeal":
                    sealType = "CONTRACT";
                    break;
                case "financialSeal":
                    sealType = "FINANCE";
                    break;
                default:
                    sealType = "ALL";
            }
            return sealType;
        } else {
            return "ALL";
        }

    }
}
